import os
import socket
import threading
class chat_server():
    def __init__(self,host,port,outtime=100,listen=5):
        self.server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.server.bind((host,port))
        self.server.listen(listen)
        self.users_data={'wr440':'84906440'}
        self.clients=[]
    #开始运行
    def run(self):
        while True:
            client,addr=self.server.accept()
            self.client_login(client)
            self.clients.append(client)
            threading.Thread(target=self.__send_msg,args=(client,)).start()
    #用户登录
    def client_login(self,client):
        msg=client.recv(1024)#接收登录数据
        if ":" in msg.decode():
            username,password=msg.decode().split(":")#解析登录数据
            if username in self.users_data.keys():
                if password==self.users_data[username]:
                    client.send("login success".encode('utf-8'))
                else:
                    client.send("error password,disconnect!".encode('utf-8'))
                    client.close()
            else:
                client.send("error username,disconnect!".encode('utf-8'))
                client.close()
        else:
            client.send("error login msg,disconnect!")
            client.close()


    #接收用户消息然后广播
    def __send_msg(self,client):
        while True:
            try:
                msg=client.recv(1024)
            except:
                self.clients.remove(client)
                client.close()
                break
            for c in self.clients:
                if c==client:
                    pass
                else:
                    c.send(msg)
def main():
    host='192.168.0.151'
    port=9999
    cs=chat_server(host,port)
    cs.run()
if __name__=='__main__':
    main()


